package com.ruoyi.hospital.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.hospital.entity.HospitalLoginBody;
import com.ruoyi.hospital.entity.LoginHospital;
import com.ruoyi.hospital.service.HospitalLoginService;
import com.ruoyi.hospital.service.HospitalPermissionService;
import com.ruoyi.hospital.service.HospitalTokenService;
import com.ruoyi.service.service.IServiceNurseitemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 登录控制
 *
 * @author ZDL
 */
@RestController
@RequestMapping("/appHospital")
public class HospitalLoginController
{
    @Autowired
    private HospitalLoginService loginService;

    @Autowired
    private HospitalTokenService tokenService;

    @Autowired
    private IServiceNurseitemsService menuService;

    @Autowired
    private HospitalPermissionService permissionService;



    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/loginHospital")
    public AjaxResult login(@RequestBody HospitalLoginBody loginBody, HttpServletRequest request)
    {
        LoginHospital oldLogin = tokenService.getLoginUser(request);
        if (oldLogin != null){
            return AjaxResult.error("请先退出当前账号！");
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginApp(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), 2);
        LoginHospital oldHospital = tokenService.getLoginUserByTk(token);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put(Constants.TOKEN, token);
        dataMap.put("userId", oldHospital.getUserId());
        dataMap.put("userName", oldHospital.getUser().getNurseName());
        dataMap.put("userTel", oldHospital.getUser().getNurseTelephonenumber());
        dataMap.put("userWard", oldHospital.getUser().getNurseWardid());
        if (oldHospital.getUser().getNurseRoleid() == 1){
            dataMap.put("userRole", "NURSE_HEAD");
        }
        if (oldHospital.getUser().getNurseRoleid() == 2){
            dataMap.put("userRole", "NURSE");
        }
        dataMap.put("userRate", 5);
        dataMap.put("userAvatar", oldHospital.getUser().getNurseAvatar());
        dataMap.put("lastLoginTime", oldHospital.getUser().getNurseLoginDate());
        dataMap.put("hospitalId", 1);
        //dataMap.put("hospitalName", "西峰区人民医院");
        dataMap.put("hospitalName", "东华数字医院");

        ajax.put("data", dataMap);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    ///**
    // * 获取路由信息
    // *
    // * @return 路由信息
    // */
    //@GetMapping("getRouters")
    //public AjaxResult getRouters()
    //{
    //    Long userId = SecurityUtils.getUserId();
    //    List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
    //    return AjaxResult.success(menuService.buildMenus(menus));
    //}

    /**
     * 退出登录方法
     * @return 结果
     */
    @Anonymous
    @PostMapping("/logoutHospital")
    public AjaxResult onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        AjaxResult result = new AjaxResult(200, "退出成功！");
        try {
            LoginHospital loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser))
            {
                String userName = loginUser.getUsername();
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getToken());
                // 记录用户退出日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
            }else{
                result = new AjaxResult(400, "缓存信息错误！");
            }
            //ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
        }catch (Exception e){
            result = new AjaxResult(400, e.getMessage());
        }finally {
            return result;
        }
    }



    /**
     * 获取统计假数据方法
     *
     * @param
     * @return 结果
     */
    @GetMapping("/getStatistics")
    public AjaxResult getStatistics(HttpServletRequest request) {
        try {
            //if(!hospitalTokenFilter.doFilterInternal(request)) {
            //    AjaxResult ajaxResult = new AjaxResult();
            //    ajaxResult.put("code", 401);
            //    ajaxResult.put("msg", "用户信息过期，请重新登录");
            //    return ajaxResult;
            //}
            //LoginHospital oldHospital = tokenService.getLoginUser(request);
            //if (oldHospital.getUserId() == null) {
            //    return AjaxResult.warn("用户信息错误");
            //}
            Map<String, Object> statistics = loginService.getStatistics();

            return AjaxResult.success("获取成功", statistics);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }



}
